package cn.dgut.training.controller;

import cn.dgut.training.dto.BaseDTO;
import cn.dgut.training.dto.Wxuser;
import cn.dgut.training.entity.activity.Carousel;
import cn.dgut.training.entity.goods.Category;
import cn.dgut.training.entity.user.User;
import cn.dgut.training.utils.Code2Session;
import cn.dgut.training.utils.RestUtil;
import cn.dgut.training.utils.UserTokenUtil;
import cn.dgut.training.vo.BaseVO;
import cn.dgut.training.vo.CommonResponse;
import cn.dgut.training.vo.UserVO;
import cn.dgut.training.wxprogress.KaGou;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

@RestController
@Slf4j
@RequestMapping("/index")
public class IndexController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private GoodsService goodsService;

    @RequestMapping("/homepage")
    public Object homepage() throws Exception{


        //先从缓存中查找


        Map<String, Object> map = new HashMap<>();
        //新上商品
        map.put("newGoodsList", goodsService.queryByNew());
        //热门商品
        map.put("hotGoodsList", goodsService.queryByHot());
        //团购
        map.put("grouponList", null);
        //分类和分类下的商品
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Callable<List>   floorGoodsList= () -> goodsService.getCategoryList();
        FutureTask<List> floorGoodsListTask = new FutureTask<>(floorGoodsList);
        executorService.submit(floorGoodsListTask);

        map.put("floorGoodsList", floorGoodsListTask.get());

        //轮播图
        List carousels=activityService.frontListCarousel();
        map.put("banner", carousels);
        //分类
        BaseVO baseVO=(BaseVO)RestUtil.getObject(goodsService.listFirstCategory(), BaseVO.class);
        map.put("channel", baseVO.getList());
        //优惠券
        List coupon = activityService.getTwo();
        map.put("couponList", coupon);

        return CommonResponse.success(map);
    }

    @RequestMapping("/auth/login_by_weixin/{code}")
    public Object wxLogin(@PathVariable("code") String code, @RequestBody Wxuser wxuser) {
        JSONObject jsonObject = Code2Session.getCode2SessionJsonObj(KaGou.appId, KaGou.appSecret, code);

        if (jsonObject.getString("errcode") == null) {
            User user = new User();
            user.setAvatar(wxuser.getAvatarUrl());
            user.setNickname(wxuser.getNickName());
            user.setUsername(wxuser.getNickName());
            user.setGender(wxuser.getGender());
            user.setWeixinOpenid(jsonObject.getString("openid"));
            user.setSessionKey(jsonObject.getString("session_key"));
            user.setUserLevel(1);

            String postData = JSONObject.toJSON(user).toString();

            String checkUrl = "http://shop-user:8882/user/openid/";
            CommonResponse checkResult = RestUtil.postObject(restTemplate, checkUrl, postData);
            Object checkResultData = checkResult.getData();

            //判断数据库是否存在此用户
            UserVO userVO = new UserVO();
            if (checkResultData == null){
                String createUrl = "http://shop-user:8882/user/create/";
                CommonResponse postResult = RestUtil.postObject(restTemplate, createUrl, postData);
                Object postResultData = postResult.getData();
                BeanUtil.copyProperties(postResultData,userVO);
                CommonResponse commonResponse=userService.create(userVO.getId());
            }else {
                BeanUtil.copyProperties(checkResultData,userVO);
            }

            String token = UserTokenUtil.generateToken(userVO.getId());
            Map<Object, Object> result = new HashMap<Object, Object>();
            result.put("token", token);
            result.put("userInfo", user);

            return CommonResponse.success(result);
        } else {
            return CommonResponse.fail(jsonObject.getString("hints"));
        }
    }

}
